﻿Imports System.Text
Imports System.ComponentModel.Composition
Imports Microsoft.VisualStudio.RegularExpression.UI
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Utilities
Imports Microsoft.VisualStudio.Text.Editor
Imports System.Windows.Controls

Namespace Microsoft.VisualStudio.RegularExpression
    ''' <summary>
    ''' Regular expression editor service.
    ''' </summary>
    <Export(GetType(RegexEditorService))>
    Friend Class RegexEditorService

        <Import()>
        Private Property TextEditorFactoryService As ITextEditorFactoryService

        <Import()>
        Private Property TextBufferFactoryService As ITextBufferFactoryService

        <Import()>
        Private Property ContentTypeRegistryService As IContentTypeRegistryService

        ''' <summary>
        ''' Shows the regex editor.
        ''' </summary>
        ''' <returns>The regular expression.</returns>
        Friend Function ShowEditor() As RegexEditorResult
            Return Me.ShowEditor(String.Empty)
        End Function

        ''' <summary>
        ''' Shows the regex editor.
        ''' </summary>
        ''' <param name="pattern">The regular expression to be edited.</param>
        ''' <returns>The regular expression.</returns>
        Friend Function ShowEditor(ByVal pattern As String) As RegexEditorResult
            ' Create the regex editor
            Dim contentType = Me.ContentTypeRegistryService.GetContentType(RegexContentType.ContentTypeName)

            Dim textBuffer = Me.TextBufferFactoryService.CreateTextBuffer(pattern, contentType)
            Dim view = Me.TextEditorFactoryService.CreateTextView(textBuffer)
            ' TODO: RC1
            Dim editor = Me.TextEditorFactoryService.CreateTextViewHost(view, True)
            editor.TextView.Properties.AddProperty(TextViewEventManager.Key, New TextViewEventManager(editor.TextView))
            HideTextViewMargins(editor)

            Dim result = pattern
            Dim dialogResult? = RegexEditorDialog.ShowDialog(pattern, editor, result)

            Dim editorResult As New RegexEditorResult(result, dialogResult)
            Return editorResult
        End Function

        Private Sub HideTextViewMargins(ByVal view As IWpfTextViewHost)
            HideTextViewMargin(view, "Left")
            HideTextViewMargin(view, "Right")
            HideTextViewMargin(view, "Top")
            HideTextViewMargin(view, "Bottom")
        End Sub

        Private Sub HideTextViewMargin(ByVal view As IWpfTextViewHost, ByVal marginName As String)
            Dim margin = TryCast(view.GetTextViewMargin(marginName), IWpfTextViewMargin)
            If margin IsNot Nothing Then
                '                margin.VisualElement.Width = 0;
                margin.VisualElement.Visibility = System.Windows.Visibility.Collapsed
            End If
        End Sub
    End Class
End Namespace